/* 
 * File:   Input.cpp
 * Author: agu
 * 
 * Created on 31 de mayo de 2014, 13:18
 */

#include "client_Input.h"
#include <iostream>
#include <SDL2/SDL_timer.h>

Input::Input(const string path, SDL_Renderer* renderer, int x, int y) :
back(renderer, path, x, y), message(renderer, x, y) {
    //Enable text input
    SDL_StartTextInput();
    this->text = NULL;
    this->inputText = "";
    this->max=15;
}

Input::~Input() {
    //Disable text input
    SDL_StopTextInput();
    if (this->text != NULL) {
        delete this->text;
    }
}

void Input::setText(const string font, int size, Color color) {
    this->text = new Text(font, color, size);
}

void Input::setMessage(const string message) {
    this->text->setMessage(message);
    Surface surface;
    this->text->copy(surface);
    this->message.load(surface);

}

void Input::update(SDL_Event* event) {
    bool renderText = false;
    if (event->type == SDL_KEYDOWN) {
        //Handle backspace
        if (event->key.keysym.sym == SDLK_BACKSPACE && inputText.length() > 0) {
            //lop off character
            renderText = true;
            inputText.pop_back();
        }//Handle copy
        else if (event->key.keysym.sym == SDLK_c && SDL_GetModState() & KMOD_CTRL) {
            inputText = SDL_SetClipboardText(inputText.c_str());
        }//Handle paste
        else if (event->key.keysym.sym == SDLK_v && SDL_GetModState() & KMOD_CTRL) {
            inputText = SDL_GetClipboardText();
            renderText = true;
        }
    }//Special text input event
    else 
        if (event->type == SDL_TEXTINPUT) {
        //Not copy or pasting
        if (!((event->text.text[ 0 ] == 'c' || event->text.text[ 0 ] == 'C') && (event->text.text[ 0 ] == 'v' || event->text.text[ 0 ] == 'V') && SDL_GetModState() & KMOD_CTRL)) {
            //Append character
            SDL_Delay(120);
            if(int(this->inputText.size()) <= this->max)
                inputText += event->text.text;
            renderText = true;
        }
    }
    if (renderText) {
        //Text is not empty
        if (inputText != "") {
            //Render new text
                this->setMessage(this->inputText);
        }//Text is empty
        else {

            this->setMessage(" ");
        }
    }
}

void Input::render() {
    this->back.render();
    this->message.render(this->back.getX() +this->back.getWidth() /10,
                         this->back.getY() + this->back.getHeight() /30,
                            this->inputText.length()*10,
                            50);
}
